package com.wptk.filemanager.ui.file;

import android.view.MenuItem;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.wptk.filemanager.R;
import com.wptk.filemanager.ad.utils.AnalyticsUtils;
import com.wptk.filemanager.model.DialogManager;
import com.wptk.filemanager.model.file.FileBean;
import com.wptk.filemanager.model.file.FileManager;
import com.wptk.filemanager.model.file.FileUtils;
import com.wptk.filemanager.model.file.Music;
import com.wptk.filemanager.ui.base.BaseActivity;
import com.wptk.filemanager.ui.file.adapter.ApkAdapter;
import com.wptk.filemanager.utils.ThreadManager;
import com.wptk.filemanager.utils.Utils;
import com.kathline.library.util.ZFileUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ApkActivity extends BaseActivity implements ApkAdapter.OnLongClickListener, View.OnClickListener, ApkAdapter.OnClickListener {


    private RecyclerView rvApk;
    private ApkAdapter apkAdapter;
    private List<FileBean> apks = new ArrayList<>();

    private SwipeRefreshLayout refreshLayout;
    private LinearLayout emptyLayout;
    private LinearLayout modifyLl;
    private TextView renameTv;
    private TextView deleteTv;
    //全部勾选框
    private CheckedTextView checkAll;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_apk;
    }

    @Override
    protected void initView() {
        AnalyticsUtils.INSTANCE.logEvent("ckapks");
        rvApk = findViewById(R.id.rv_apk);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        modifyLl = (LinearLayout) findViewById(R.id.modify_ll);
        renameTv = findViewById(R.id.rename_tv);
        deleteTv = findViewById(R.id.delete_tv);
        refreshLayout = findViewById(R.id.refreshLayout);
        emptyLayout = findViewById(R.id.emptyLayout);
        checkAll = findViewById(R.id.cb_all_toolbar);

        rvApk.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void initEvent() {

        renameTv.setOnClickListener(this);
        deleteTv.setOnClickListener(this);
        toolbar.setTitle(getString(R.string.apks));
        refreshLayout.setEnabled(false);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        checkAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAll.toggle();
                apkAdapter.checkAll(checkAll.isChecked());
                checkState();
            }
        });


        apkAdapter = new ApkAdapter();
        apkAdapter.setOnClickListener(this);
        apkAdapter.setOnLongClickListener(this);
        rvApk.setAdapter(apkAdapter);
        getData();
    }

    private void getData() {
        refreshLayout.setRefreshing(true);
        ThreadManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                apks = FileManager.getInstance(Utils.getContext()).getFilesByType(FileUtils.TYPE_APK);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (apks == null || apks.size() == 0) {
                            apkAdapter.clear();
                            emptyLayout.setVisibility(View.VISIBLE);
                        } else {
                            apkAdapter.setDatas(apks);
                            rvApk.scrollToPosition(0);
                            emptyLayout.setVisibility(View.GONE);
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    @Override
    public void onLongClick() {
        //长安开启选择模式
        updateSelectMode(true);
        checkState();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rename_tv:
                /*if(apkAdapter.getSelectApks().isEmpty()){
                    showToast("请先选择要更名的文件");
                    return;
                }*/
                final FileBean renameFile = apkAdapter.getSelectApks().get(0);
                DialogManager.renameDialog(ApkActivity.this
                        , renameFile.getFilePath()
                        , renameFile.getFileName()
                        , new DialogManager.OnRenameListener() {
                            @Override
                            public void onSuccess(String newName, String newPath) {
                                updateSelectMode(false);
                                //更新数据
                                renameFile.setFilePath(newPath);
                                renameFile.setFileName(newName);
                                apkAdapter.notifyDataSetChanged();
                                //getData();
                                //showToast("rename success");
                            }

                            @Override
                            public void onFailed() {
                                showToast("Rename failure");
                            }
                        });
                break;
            case R.id.delete_tv:
                DialogManager.deleteFileDialog(ApkActivity.this, new DialogManager.OnDialogClickListener() {
                    @Override
                    public void onOKClick(Object data) {
                        //即将删除的文件路径
                        List<String> deleteFilePaths = new ArrayList<>();
                        //需要adapter更新的item位置
                        final Set<Integer> positions = new HashSet<>();

                        //遍历选中的数据
                        for (FileBean fileBean : apkAdapter.getSelectApks()) {
                            //拿到当前数据的路径
                            final String beanPath = fileBean.getFilePath();
                            //删除此文件
                            if(com.wptk.filemanager.utils.FileUtils.deleteFile(beanPath)){
                                deleteFilePaths.add(beanPath);
                            }
                        }
                        //showToast("delete success for "+deleteFilePaths.size()+" file");
                        //通知数据库更新已经删除的路径文件
                        notifyFileIsDeleted(deleteFilePaths);

                        updateSelectMode(false);
                        getData();
                    }
                });
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //选择状态下，点击左上角 x 取消选中模式
                //清空已选择数据 恢复勾选数据 导航重置为返回键
                if (apkAdapter.isSelectModel()) {
                    updateSelectMode(false);
                } else {
                    //非选择状态，结束
                    finish();
                }
        }
        return true;
    }

    private void updateSelectMode(boolean isSelectedMode) {
        if(isSelectedMode){

            modifyLl.setVisibility(View.VISIBLE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.cancle));
            checkAll.setVisibility(View.VISIBLE);
        }else{
            modifyLl.setVisibility(View.INVISIBLE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.back));
            checkAll.setVisibility(View.GONE);
        }
        apkAdapter.setSelectModel(isSelectedMode);
        apkAdapter.getSelectApks().clear();
        apkAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view, FileBean fileBean) {
        if(apkAdapter.isSelectModel()){
            checkState();
        }else{
            //
            ZFileUtil.openFile( fileBean.getFilePath(), view);
        }
    }

    private void checkState() {

        if (apkAdapter.getSelectApks().size() == 1) {
            renameTv.setEnabled(true);
        } else {
            renameTv.setEnabled(false);
        }
        if (apkAdapter.getSelectApks().size() == 0) {
            deleteTv.setEnabled(false);
        } else {
            deleteTv.setEnabled(true);
        }
    }
}